package com.leyou.item.filter;

import com.leyou.common.pojo.UserInfo;
import com.leyou.common.util.CookieUtils;
import com.leyou.common.util.JwtUtils;
import com.leyou.item.config.FilterProperties;
import com.leyou.item.config.JwtProperties;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.http.HttpStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author shkstart
 * @create 2020-05-11 20:12
 */

@Component
public class LoginFilter extends ZuulFilter {

    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private FilterProperties filterProperties;

    //过滤器级别  pre在请求路由前调用  route在请求路由时调用  post在route和error后调用
    @Override
    public String filterType() {
        return "pre";
    }

    //有限级别  数值越小级别越高
    @Override
    public int filterOrder() {
        return 20;
    }

    //是否执行过滤器  true是执行  false不执行
    @Override
    public boolean shouldFilter() {
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        //获取请求的url
        String url = request.getRequestURI();
        //获取配置文件中要忽略的路径
        List<String> allowPaths = filterProperties.getAllowPaths();
        //循环判断是否包含   如果包含就放行
        for (String allowPath : allowPaths) {
            if (url.contains(allowPath)){
                return false;
            }
        }
        return true;
    }

    //逻辑性代码
    @Override
    public Object run() throws ZuulException {

        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        //获取token
        String token = CookieUtils.getCookieValue(request, jwtProperties.getCookieName());
        try {
            //获取userinfo
            UserInfo userinfo = JwtUtils.getInfoFromToken(token, jwtProperties.getPublicKey());

        } catch (Exception e) {
            e.printStackTrace();
            //没有找到就不放行
            currentContext.setSendZuulResponse(false);
            //设置相应状态码
            currentContext.setResponseStatusCode(HttpStatus.SC_UNAUTHORIZED);
        }


        return null;
    }
}
